package logic

import (
	"context"
	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"
	"fmt"
	"strconv"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type ServeyUpdateLogic struct{
	logx.Logger
	ctx context.Context
	rds *redis.Redis
	svcCtx *svc.ServiceContext
	modelS model.ServeyModel
	modelSSC model.SevSevClfModel
	modelSC model.ServeyClassifyModel
}

func NewServeyUpdateLogic(ctx context.Context,svcCtx *svc.ServiceContext)*ServeyUpdateLogic{
	rds, err := redis.NewRedis(redis.RedisConf{
		Host: svcCtx.Config.Redis.Host,
		Pass: svcCtx.Config.Redis.Pass,
		Type: svcCtx.Config.Redis.Type,
	})
	if err != nil {
		logx.Errorf("redis init error: %v", err)
	}
	return &ServeyUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx: ctx,
		svcCtx: svcCtx,
		rds: rds,
		modelS: model.NewServeyModel(svcCtx.Orm,svcCtx.Config.Cache),
		modelSSC: model.NewSevSevClfModel(svcCtx.Orm),
		modelSC: model.NewServeyClassifyModel(svcCtx.Orm,svcCtx.GormDB),
	}
}

func (l *ServeyUpdateLogic)Update(req *types.ServeyUpdateRequest)(resp *types.CommonResponse,err error){
	payload,ok := l.ctx.Value("payload").(string)
	if !ok{
		return nil,errorx.NewBizError(500,"用户ID获取失败")
	}
	userId,err := strconv.ParseInt(payload,10,64)
	if err != nil{
		return nil,errorx.NewBizError(500,"字符串格式转换错误")
	}
	err = l.modelS.Trans(l.ctx,func(context context.Context, session sqlx.Session) error {

		// step1 update servey

		servey,err := l.modelS.FindOne(context,nil ,req.Id)
		if err != nil || servey.IsDeleted == deleted{
			fmt.Println("报错出现的问题是：",err)
			return errorx.NewBizError(500,"未查询到此问卷～～")
		}
		if servey.CreatorId != userId {
			return errorx.NewBizError(500,"非本问卷创建人，不能修改本问卷～～")
		}
		l.rds.DelCtx(l.ctx,ServeyDetailPrefix + strconv.FormatInt(req.Id,10))
		if len(strings.TrimSpace(req.Title)) > 0 {
			servey.Title = req.Title
		}
		if len(strings.TrimSpace(req.Description)) > 0{
			servey.Description = req.Description
		}
		err = l.modelS.Update(context,session,servey)
		if err != nil {
			return errorx.NewBizError(500,"更新失败")
		}
		// step2 update sev_sev_clf
		if len(req.DelSevClfIds) > 0 {
			err = l.modelSSC.BulkDelete(context,session,req.DelSevClfIds,req.Id)
			if err != nil {
				return errorx.NewBizError(500,"数据库更新异常")
			}
		}
		if len(req.AddSevClfIds) > 0 {
			err = l.modelSSC.BulkInsert(context,session,req.AddSevClfIds,req.Id)
			if err != nil {
				return errorx.NewBizError(500,"数据库更新异常")
			}
		}
		// step3 update servey_classify
		if len(req.DelSevClfIds) > 0 {
			err = l.modelSC.RowsUpdateNum(context,session,1,1,req.DelSevClfIds)
			if err != nil {
				return errorx.NewBizError(500,"数据库更新异常")
			}
		}
		if len(req.AddSevClfIds) > 0 {
			err = l.modelSC.RowsUpdateNum(context,session,0,1,req.AddSevClfIds)
			if err != nil {
				return errorx.NewBizError(500,"数据库更新异常")
			}
		}
		return nil
	})
	if err != nil {
		return nil,err
	}
	return &types.CommonResponse{
		Code: 200,
		Msg: "修改成功",
	},nil
}